# -*- -*- -*- -*- -*- -*- -*-
# @Author  : mengzhe
# @Time    : 2025/1/13 16:40
# @File    : weather_station.py
# @function: 气象站行指令集  weather_station
# @input   :
# @output  :
# @Software: PyCharm 
# -*- -*- -*- -*- -*- -*- -*-
import  subprocess
from cgitb import reset

import utils
import serial
import time
import datetime

# 定义指令集合
commands = {
    "active_escalation":    "[0x01, 0x03, 0x01, 0xF4, 0x00, 0x0C, 0x05, 0xC1]",

    # 更多指令可以继续添加...
}

# 使用字典中的命令
def execute_command(command_name):
    command = commands.get(command_name)
    if command:
        result = subprocess.getoutput(command)
        return result
    else:
        return f"Command '{command_name}' not found."


class WEATHER:
    def __init__(self, sensor_id, name):
        self.sensor_id = sensor_id
        self.name = name
        self.status = "IDLE"

        self.wind_speed             ="00 00 "  # 风速
        self.wind_force             ="00 00 "       # 风力
        self.wind_level             ="00 00 "       # 风级
        self.wind_direction         ="00 00 "       # 风向
        self.humidity               ="00 00 "       # 湿度
        self.temperature            ="00 00 "       # 温度
        self.noise                  ="00 00 "       # 噪声
        self.pm25                   ="00 00 "       # PM2.5
        self.pm10                   ="00 00 "       # PM10
        self.atmospheric_pressure   ="00 00 "       # 大气压
        self.lux                    ="00 00 "        # lux
        self.rainfall               ="00 00 "        # 雨量
        self.received_crc_low       ="00 00 "        # CRC校验码
        self.received_crc_high      ="01 00 "        # CRC校验码
        self.device_serial          ="00 00 "          #设备串口

    def active_escalation(self):
        # 测试指令集合
        # 55 AA 01 00 00 00 04 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00
        # 主动上报
        try:
            self.device_serial=serial.Serial('/dev/ttyUSB1', 4800)

            data = bytearray([0x01, 0x03, 0x01, 0xF4, 0x00, 0x0C, 0x05, 0xC1])
            self.device_serial.write(data)

            # 持续读取串口数据，设置短超时
            start_time = time.time()
            received_data = b''
            while time.time() - start_time < 0.5:  # 等待 0.5 秒
                new_data = self.device_serial.read(self.device_serial.in_waiting)  # 读取缓冲区中的所有数据
                if new_data:
                    received_data += new_data
                    start_time = time.time()  # 重置计时

            # 获取当前时间，用于打印接收时间
            current_time = datetime.datetime.now()
            receive_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")

            # 打印接收信息
            result = ' '.join(f'{byte:02X}' for byte in received_data)
            print(f"{receive_time_str} 气象站主动上报: {result}")
            WEATHER.decode_data(received_data)
            print('返回值：'+result)
            result = utils.str_bytes_2_bytes(result)
        except:
            result = 'FF FF FF FF'

        return result

    def test(self):
        result = 'weather station update'
        return result
    def read_data(self):
        # 模拟从传感器读取数据
        return f"Data from {self.name} (ID: {self.sensor_id})"

    def configure(self, params):
        # 模拟传感器配置
        self.status = "CONFIGURED"
        return f"{self.name} configured with {params}"

    def reset(self):
        # 模拟传感器复位
        self.status = "IDLE"
        return f"{self.name} reset to default state"

    def decode_data(received_data):
        # 气象站数据解析
        address_code = received_data[0]
        function_code = received_data[1]
        valid_byte_count = received_data[2]

        # 风速值（假设为整数，单位：m/s）
        wind_speed = float((received_data[3] << 8) | received_data[4]) / 100.0
        # 风力（假设为整数）
        wind_force = (received_data[5] << 8) | received_data[6]
        # 风级（假设为整数）
        wind_level = (received_data[7] << 8) | received_data[8]
        # 风向（假设为整数，单位：度）
        wind_direction = (received_data[9] << 8) | received_data[10]
        # 湿度（假设为整数，单位：%）
        humidity = float((received_data[11] << 8) | received_data[12]) / 10  # 湿度数据需要除以 10 得到实际值

        # 温度（假设为浮点数，单位：℃）
        temperature = float((received_data[13] << 8) | received_data[14]) / 10  # 假设温度数据需要除以 10 得到实际值
        # 噪声（假设为整数，单位：dB）
        noise = float((received_data[15] << 8) | received_data[16]) / 10
        # PM2.5（假设为整数，单位：μg/m³）
        pm25 = (received_data[17] << 8) | received_data[18]
        # PM10（假设为整数，单位：μg/m³）
        pm10 = (received_data[19] << 8) | received_data[20]
        # 大气压（假设为浮点数，单位：kPa）
        atmospheric_pressure = float((received_data[21] << 8) | received_data[22]) / 10  # 大气压数据需要除以 100 得到实际值
        # Lux（假设为整数）
        lux = (received_data[23] << 8) | received_data[24]

        # 雨量（假设为浮点数，单位：mm）
        rainfall = float((received_data[25] << 8) | received_data[26]) / 10  # 假设雨量数据需要除以 10 得到实际值

        # 提取接收到的 CRC 校验码
        received_crc_low = received_data[27]
        received_crc_high = received_data[28]

        # 计算预期的 CRC 校验码
        expected_crc = utils.calculate_crc(received_data[:-2])  # 对除最后两个字节外的数据计算 CRC

        expected_crc_low = expected_crc & 0xFF  # 取低字节
        expected_crc_high = (expected_crc >> 8) & 0xFF  # 取高字节

        # CRC检校，成功后保存在对应文件夹
        if received_crc_low == expected_crc_low and received_crc_high == expected_crc_high:

            # 写入 WeatherStation.txt
            output_str = f"CRC 校验通过,风速: {wind_speed} m/s, 风力: {wind_force}级, 风向: {wind_level}档, 风向: {wind_direction} 度, 湿度: {humidity} %RH, 温度: {temperature} ℃, 噪声: {noise} dB, PM2.5: {pm25} μg/m³, PM10: {pm10} μg/m³, 大气压: {atmospheric_pressure} kPa, 光照: {lux}, 雨量: {rainfall} mm"
            print(output_str)
        else:
            print(f"CRC 校验失败")



